#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc, COOPIP_Form, COOPIP_Authentication
import djangoproject.models.intranet, djangoproject.models.ipbase, djangoproject.models.revenueprotection
from django.contrib.gis.geos import *
#import GIS

def BuildMeterPingReportForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['AllMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllAMRFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['AllSubstationFailureMeterIndicator']=forms.BooleanField(required=False)
    Dict['TopOneIndicator']=forms.BooleanField(required=False)
    Dict['SerialNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['Substation']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['StartDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['EndDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    return Dict

def ProcessMeterPingReportForm(form, Username, request):
    AllMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllMeterIndicator')
    AllFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllFailureMeterIndicator')
    AllAMRFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllAMRFailureMeterIndicator')
    AllSubstationFailureMeterIndicator=COOPIP_Form.FormGetBoolean(form, 'AllSubstationFailureMeterIndicator')
    TopOneIndicator=COOPIP_Form.FormGetBoolean(form, 'TopOneIndicator')
    SerialNumber=COOPIP_Form.FormGetString(form, 'SerialNumber')
    Substation=COOPIP_Form.FormGetString(form, 'Substation')    #TODO
    StartDate=COOPIP_Form.FormGetDateTime(form, 'StartDate')
    EndDate=COOPIP_Form.FormGetDateTime(form, 'EndDate')

   
    if(AllMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().order_by('SerialNumber')
    elif(AllFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='failed').order_by('SerialNumber')
    elif(AllAMRFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='amrfailure').order_by('SerialNumber')
    elif(AllSubstationFailureMeterIndicator):
        Meters=djangoproject.models.ipbase.Meter.objects.all().filter(Symbology='substationfailure').order_by('SerialNumber')
    elif(SerialNumber):
        Meters=djangoproject.models.ipbase.Meter.objects.filter(SerialNumber=SerialNumber)
    else:
        return []
    if(not StartDate):
        StartDate=datetime.datetime.now() - datetime.timedelta(days=2)
    if(not EndDate):
        EndDate=datetime.datetime.now() + datetime.timedelta(days=2)
    MeterPings=[]
    for meter in Meters:
        TempMeterPings=djangoproject.models.ipbase.MeterPing.objects.filter(Meter=meter).filter(DateTime__gte=StartDate).filter(DateTime__lte=EndDate).order_by('DateTime')
        for meterPing in TempMeterPings:
            MeterPings.append(meterPing)
            if(TopOneIndicator):
                break
    return MeterPings

        

def BuildMeterPingConfigurationForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['OffIndicator']=forms.BooleanField(required=False)
    Dict['LowIndicator']=forms.BooleanField(required=False)
    Dict['NormalIndicator']=forms.BooleanField(required=False)
    Dict['HighIndicator']=forms.BooleanField(required=False)
    return Dict

 
def ProcessMeterPingConfigurationtForm(form, Username, request):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    OffIndicator=COOPIP_Form.FormGetBoolean(form, 'OffIndicator')
    LowIndicator=COOPIP_Form.FormGetBoolean(form, 'LowIndicator')
    NormalIndicator=COOPIP_Form.FormGetBoolean(form, 'NormalIndicator')
    HighIndicator=COOPIP_Form.FormGetBoolean(form, 'HighIndicator')
    #Valid Statuses:  off, low, normal, high
    NewStatus="normal"
    if(HighIndicator):
        NewStatus="high"
    if(NormalIndicator):
        NewStatus="normal"
    if(LowIndicator):
        NewStatus="low"
    if(OffIndicator):
        NewStatus="off"
    if(UpdateIndicator):
        djangoproject.models.ipbase.COOPIPSetting.SetPingRate(NewStatus, Username)
   

def PopulateMeterPingConfigurationForm(form):
    form.setData({'UpdateIndicator': False})
    form.setData({'HighIndicator':  False})
    form.setData({'NormalIndicator':  False})
    form.setData({'LowIndicator':  False})
    form.setData({'OffIndicator':  False})
    return form




class FakeForm():
    def __init__(self, data):
        self.data=data


